package com.qbccn.blog.config.exception;

import com.alibaba.fastjson.JSONObject;
import com.qbccn.blog.dto.ResponseCode;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author linke
 * @date 2019-12-28 下午 13:10
 * @description 自定义token无效异常，只有401才能进入
 */
@Component
public class BootOAuth2AuthExceptionEntryPoint extends OAuth2AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        if (e instanceof InsufficientAuthenticationException) {
            response.setContentType("application/json;charset=UTF-8");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", ResponseCode.INVALID_TOKEN);
            jsonObject.put("message", "无效的凭据");
            jsonObject.put("data", e.getMessage());
            response.getWriter().write(jsonObject.toString());
        }
    }
}
